package com.stox.navigator.ui.swing.view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.util.Collections;
import java.util.List;

import com.stox.core.ui.swing.util.SwingUtil;
import com.stox.core.ui.swing.view.InternalFrameView;
import com.stox.core.ui.swing.widget.VTextIcon;
import com.stox.core.ui.swing.wrapper.JTabbedPane;
import com.stox.core.ui.swing.wrapper.JTree;
import com.stox.design.Callback;
import com.stox.design.Holder;
import com.stox.design.Ordered.OrderComparator;
import com.stox.ioc.Container;
import com.stox.resources.i18n.MessageSource;

public class NavigatorView extends InternalFrameView implements Holder<JTree>{
	private static final long serialVersionUID = -2292138069258977312L;
	
	private JTabbedPane tabbedPane = new JTabbedPane(){
		private static final long serialVersionUID = 3588208810928628057L;

		public void setSelectedIndex(int index) {
			final NavigatorTab tab = (NavigatorTab)getComponentAt(index);
			if(tab != null && !tab.isInitialized()){
				
				new Thread(){
					@Override
					public void run() {
						super.run();
						SwingUtil.executeInFreeze((Component)tab,new Callback<Object,Object>(){
							@Override
							public Object execute(Object payload) {
								tab.initialize();
								return null;
							}
						}, null);
					}
				}.start();
			}
			super.setSelectedIndex(index);
		};
	};
	
	public NavigatorView() {
		super(MessageSource.getMessage("Navigator"));
	}
	
	public void afterPropertiesSet(){
		tabbedPane.setTabPlacement(JTabbedPane.LEFT);
		
		List<NavigatorTab> tabs = Container.getImplementations(NavigatorTab.class);
		Collections.sort(tabs, OrderComparator.instance);
		for(NavigatorTab tab : tabs){
			tabbedPane.addTab(null,new VTextIcon(tabbedPane, tab.getName(),  VTextIcon.ROTATE_LEFT), (Component)tab);
		}

		tabbedPane.setSelectedComponent(Container.get(ScripsPanel.class));
		getContentPane().add(tabbedPane, BorderLayout.CENTER);
	}
	
	
	@SuppressWarnings("unchecked")
	public JTree get(){
		Component component = tabbedPane.getSelectedComponent();
		if(component != null){
			return((Holder<JTree>)component).get();
		}
		return null;
	}
	
}
